#include "mainwidget.h"
#include "ui_mainwidget.h"
#include "cameracontrolrequest.h"
#include <QPainter>
#include <QDebug>
#include <QNetworkReply>

MainWidget::MainWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MainWidget)
    , _pFfmpegKits(new FFmpegKits)
    , _kPlayState(PLAYER_IDLE)
    , _hFlip(false)
    , _vFlip(false)
    , _pHttpManager(new QNetworkAccessManager(this))
{
    ui->setupUi(this);

    connect(_pFfmpegKits.get(), &FFmpegKits::sigGetOneFrame, this, &MainWidget::getOneFrame);
}

MainWidget::~MainWidget()
{
    // UI线程结束前必须先让解码线程退出并等待其退出
    _pFfmpegKits->stopPlay();
    _pFfmpegKits->wait();
    delete ui;
}

void MainWidget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setBrush(Qt::white);
    painter.drawRect(0, 0, this->width(), this->height()); // 先画成白色
    if (_image.size().width() <= 0) {
        return;
    }

    // 若当前处于停止状态，不播放视频画面，界面提示用户输入新url再按播放键
    if (_kPlayState == PLAYER_STOP) {
        painter.drawText(rect(), Qt::AlignCenter, "已停止播放，请输入新的网络地址后按播放键");
        return;
    }

    // 将图像按比例缩放
    int showWidth = this->width() - 40;
    int showHeight = this->height() - 40;
    QImage img = _image.scaled(QSize(showWidth, showHeight), Qt::KeepAspectRatio);
    img = img.mirrored(_hFlip, _vFlip);

    int x = this->width() - img.width();
    int y = this->height() - img.height();
    x /= 2;
    y /= 2;
//    qDebug() << "x:" << x << ", y:" << y;
    painter.drawImage(QPoint(x, 80), img);
}

void MainWidget::getOneFrame(QImage image)
{
    ui->imageLabel->clear();
    if (_kPlayState == PLAYER_PAUSE) {
        return;
    }
    _image = image;
    update(); // 调用后会执行paintEvent函数
}


void MainWidget::on_playButton_clicked()
{
    // 若在起始状态或停止状态下按播放键，启动解码线程解析指定url视频流，UI线程播放视频
    if (_kPlayState == PLAYER_IDLE || _kPlayState == PLAYER_STOP) {
        qDebug() << "play";
        ui->addrLineEdit->setEnabled(false);
        QString url = ui->addrLineEdit->text();
        qDebug() << "url:" << url;
        _pFfmpegKits->startPlay(url);
        ui->addrLineEdit->setText("rtsp网络连接中...");
        _kPlayState = PLAYER_PLAYING;
        ui->playButton->setText("停止");
        return;
    }
    // 若在播放状态下按播放键，结束解码线程，UI线程停止播放，提示用户输入新url再按播放键
    if (_kPlayState == PLAYER_PLAYING) {
        qDebug() << "stop";
        _pFfmpegKits->stopPlay();
        _pFfmpegKits->wait();
        _kPlayState = PLAYER_STOP;
        ui->addrLineEdit->setEnabled(true);
        ui->addrLineEdit->clear();
        ui->addrLineEdit->setPlaceholderText("rtsp://admin:admin@192.168.105.222/live/chn=0");
        ui->playButton->setText("播放");
        return;
    }
    // 若在暂停状态下按播放键，继续播放
    if (_kPlayState == PLAYER_PAUSE) {
        qDebug() << "continue";
        _kPlayState = PLAYER_PLAYING;
        ui->playButton->setText("停止");
        return;
    }
}

void MainWidget::on_pauseButton_clicked()
{
    // 若在播放状态下按暂停键，暂停播放
    if (_kPlayState == PLAYER_PLAYING) {
        qDebug() << "pause";
        _kPlayState = PLAYER_PAUSE;
        ui->pauseButton->setText("继续");
        ui->playButton->setText("播放");
        return;
    }
    // 若在暂停状态下按暂停键，继续播放
    if (_kPlayState == PLAYER_PAUSE) {
        qDebug() << "continue";
        _kPlayState = PLAYER_PLAYING;
        ui->pauseButton->setText("暂停");
        return;
    }
}

void MainWidget::on_flipButton_clicked()
{
    // 水平翻转画面
    _hFlip = !_hFlip;
}

void MainWidget::on_leftButton_clicked()
{
    cameraControl(CAMERA_LEFT);
}

void MainWidget::on_rightButton_clicked()
{
    cameraControl(CAMERA_RIGHT);
}

void MainWidget::on_upButton_clicked()
{
    cameraControl(CAMERA_UP);
}

void MainWidget::on_downButton_clicked()
{
    cameraControl(CAMERA_DOWN);
}

void MainWidget::on_leftUpButton_clicked()
{
    cameraControl(CAMERA_LEFT_UP);
}

void MainWidget::on_rightUpButton_clicked()
{
    cameraControl(CAMERA_RIGHT_UP);
}

void MainWidget::on_leftDownButton_clicked()
{
    cameraControl(CAMERA_LEFT_DOWN);
}

void MainWidget::on_rightDownButton_clicked()
{
    cameraControl(CAMERA_RIGHT_DOWN);
}

void MainWidget::cameraControl(MoveCommand command)
{
    QString url = CameraControlRequest().getMoveUrl(command);
    qDebug() << "Camera control url:" << url;
    QNetworkReply *response1 = _pHttpManager->get(QNetworkRequest(url));
    connect(response1, &QNetworkReply::finished, [response1, this]() {
        if (response1->error() != QNetworkReply::NoError) {
            qCritical() << "Camera control failed.";
            return;
        }
        qInfo() << "Camera control success.";
#if 1
        QString stopUrl = CameraControlRequest().getMoveUrl(CAMERA_STOP);
        qDebug() << "stopUrl:" << stopUrl;
        QNetworkReply *response2 = _pHttpManager->get(QNetworkRequest(stopUrl));
        connect(response2, &QNetworkReply::finished, [response2]() {
            if (response2->error() != QNetworkReply::NoError) {
                qInfo() << "Camera move stop failed.";
                return;
            }
            qInfo() << "Camera stop move success.";
        });
#endif
    });
}
